package com.loong.android.tools;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.provider.Settings;

import androidx.annotation.Nullable;

import com.loong.android.LonWin;
import com.loong.android.WinLife;

/**
 * GPS操作工具
 * 需要权限：android.permission.ACCESS_COARSE_LOCATION、android.permission.ACCESS_FINE_LOCATION
 */
public class Gps {
    private final static int REQUEST_CODE_GPS_SETTING = 789;
    private static LocationManager locationManager;
    public static LocationManager getLocationManager() {
        return locationManager;
    }

    /**
     * 对GPS组件进行初始化操作，使用GPS组件前必须执行本函数
     *
     * @param context 上下文
     */
    public static LocationManager init(Context context) {
        if (locationManager == null) {
            locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        }
        return locationManager;
    }

    /**
     * 打开系统的位置服务设置界面，当设置完成后，触发{@link OpenSettingEvent#onFinish}事件。
     * @param context 上下文
     * @param event 事件回调
     */
    public void openSettingUi(Context context, OpenSettingEvent event) {
        if(!(context instanceof Activity)) return;
        if (context instanceof LonWin) {
            LonWin win = (LonWin) context;
            final String listenerName = "GpsOpenSettingUi" + System.currentTimeMillis();
            win.addWinLifeListener(listenerName, new WinLife() {
                @Override
                public void onActivityResult(int requestCode, int resultCode, @Nullable Intent intent) {
                    super.onActivityResult(requestCode, resultCode, intent);
                    if (requestCode != REQUEST_CODE_GPS_SETTING) return;
                    win.removeWinLifeListener(listenerName);
                    if (event != null) event.onFinish();
                }
            });
        }
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        ((Activity) context).startActivityForResult(intent, REQUEST_CODE_GPS_SETTING);
    }

    /**
     * 打开系统设置界面后的接口事件
     */
    public abstract static class OpenSettingEvent {
        /**
         * 设置完毕
         */
        public void onFinish() {

        }
    }
}
